<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  
  <script type="text/javascript">
    var obj = {
      name: 'xxx',
      age: 18,
      info: {
        bobby: ['travel', 'piano', {
          a: 9
        }],
        career: {
          teacher: 9,
          enginer: 6
        }
      }
    }

    // ES5 深拷贝
    function deepClone (origin, target) {
      var tar = target || {};
      var toStr = Object.prototype.toString;
      var arrType = '[object Array]'
      for (var k in origin){
        if(origin.hasOwnProperty(k)) {
          if (typeof origin[k] === 'object' && origin !== null) {
            tar[k] = toStr.call(origin[k]) === arrType ? [] : {};
            deepClone(origin[k], tar[k]);
          } else {
            tar[k] = origin[k];
          }
        }
      }
      return tar;
    }

    // ES6 深拷贝
    function deepClone2(origin, hashMap = new WeakMap()) {
      if(origin == undefined || typeof origin !== 'object') {
        return origin;
      }
      if(origin instanceof Date){
        return new Date(origin)
      }
      if(origin instanceof RegExp) {
        return new RegExp(origin);
      }
      const hashKey = hashMap.get(origin);
      if(hashKey) {
        return hashKey;
      }
      var target = origin.constructor();
      hashMap.set(origin, target);
      for(var k in origin) {
        target[k] = deepClone2(origin[k], hashMap);
      }

      return target;
    }

    var newobj = deepClone(obj);
    console.log(obj);
    newobj.info.bobby = {a: 3}
    console.log(newobj);


    var newobj2 = deepClone2(newobj);
    console.log(obj);
    newobj2.info.bobby = ["asd", "deepClone"]
    console.log(newobj2)

    var test1 = {}
    var test2 = {}
    test1.test2 = test2;
    test2.test1 = test1;
    console.log(deepClone2(test1));
  </script>
</body>
</html>